import { DirectiveBinding } from 'vue';

import { useUserStore } from '@/store';

// 权限指令类型
type PermissionDirective = {
  mounted(el: HTMLElement, binding: DirectiveBinding): void;
  updated(el: HTMLElement, binding: DirectiveBinding): void;
};

// 检查权限
function checkPermission(value: string | string[]): boolean {
  const permissionStore = useUserStore();
  const { permissions } = permissionStore;

  if (!value) return false;

  if (typeof value === 'string') {
    return permissions.includes(value);
  }

  if (Array.isArray(value)) {
    return value.some((permission) => permissions.includes(permission));
  }

  return false;
}

// 处理DOM元素的显示/隐藏或禁用
function handlePermission(el: HTMLElement, binding: DirectiveBinding): void {
  const { value, modifiers } = binding;

  const hasPermission = checkPermission(value);

  if (!hasPermission) {
    if (modifiers.disable) {
      el.setAttribute('disabled', '');
      el.classList.add('permission-disabled');
    } else {
      el.parentNode?.removeChild(el);
    }
  }
}

// 创建权限指令
export const permission: PermissionDirective = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    handlePermission(el, binding);
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    handlePermission(el, binding);
  },
};

// 注册指令
export default {
  install(app: any) {
    app.directive('permission', permission);
  },
};
